package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.apuser.UserFeignClient;
import com.heima.comment.dtos.CommentSaveDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentListDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApUserThreadLocalUtil;
import com.heima.utils.common.AppThreadLocal;
import org.apache.commons.math3.util.ResizableDoubleArray;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeignClient userFeignClient;


    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户是否是已登录
        ApUser apUser = AppThreadLocal.getApUser();
        Integer userId = apUser.getId();
        if(userId==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(dto.getContent()==null||dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询用户信息
            //1.插缓存
            //2.查数据库
        String apUserStr = redisTemplate.opsForValue().get("LOGIN_USER_" + userId);
        if(StringUtils.isEmpty(apUserStr)){
            ResponseResult<ApUser> result = userFeignClient.findUserById(userId.longValue());
            if(result.getCode()==200 && result.getData()!=null){
                apUser = result.getData();
                redisTemplate.opsForValue().set("LOGIN_USER_" + userId, JSON.toJSONString(apUser), 2, TimeUnit.HOURS);
            }
        }else {
            apUser = JSON.parseObject(apUserStr, ApUser.class);
        }

        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // TODO: 2023/3/3  安全信息过滤
        //5.保存数据到mongo中
        ApComment apComment = new ApComment();
        apComment.setId(ObjectId.get().toHexString());
        apComment.setUserId(apUser.getId());
        apComment.setNickName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setTargetId(dto.getArticleId().toString());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        mongoTemplate.insert(apComment);
        return ResponseResult.okResult("评论成功");
    }

    @Override
    public ResponseResult findByArticleId(CommentListDto dto) {
        //1.检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), 50));

        //2根据文章id去查询mongo的评论表，并进行分页和排序展示
        Query query=Query.query(Criteria.where("targetId").is(dto.getArticleId().toString())
                .and("createdTime").lt(dto.getMinDate())).with(Sort.by(Sort.Direction.DESC,"createdTime")) //排序
                .limit(dto.getSize()); //分页
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        if(commentList==null && commentList.size()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.如果此刻是游客登录的话，则直接返回评论列表
        ApUser user = AppThreadLocal.getApUser();
        if(user.getId()==0){
            return ResponseResult.okResult(commentList);
        }
        //4.否则就是用户登录，加载数据的时候，要判断当前用户点赞了拿些评论，并给予标识
        //4.1 查询redis中是否有点赞数据
        String key="COMMENT_LIKE_"+user.getId();
        //根据key查询出所有的值
        Set<String> like_ids = redisTemplate.opsForSet().members(key);
        //4.2 如果没有查询到数据,则直接返回评论列表
        if(like_ids==null){
            return ResponseResult.okResult(commentList);
        }
        //4.3 否则，就是存在点赞数据，则添加标记
        List<ApCommentVo> resultList = commentList.stream().map(comment -> {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(comment, vo);
            if (like_ids.contains(comment.getId())) {
                vo.setOperation((short) 0);
            }
            return vo;

        }).collect(Collectors.toList());
        //5. 返回数据

        return ResponseResult.okResult(resultList);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //判断参数
        if(dto==null||dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户是否登录
        ApUser apUser = AppThreadLocal.getApUser();
        if(apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.5 判断如果是游客身份则不允许发表评论
        if(apUser.getId()==0){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请登录之后再来点赞！！");
        }

        //判断当前评论信息是否存在，如果不存在，直接返回
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(apComment==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String comment_likes_key="COMMENT_LIKE_"+apUser.getId();

        //表示根据当前key下的所有的value中是否包含某一个，如果包含返回true,否则false
        Boolean memberFlag = redisTemplate.opsForSet().isMember(comment_likes_key, dto.getCommentId());

        //4 如果点赞过，并且现在正在执行的是点赞操作，直接返回
        if(memberFlag && dto.getOperation()==0){
            return ResponseResult.okResult("小傻呗已经点过赞了");
        }
        //如果点赞过，并且正在执行的是取消点赞，删除redis,删除mongo中点赞集合，修改mongo中的评论集合，点赞数-1
        if(memberFlag&&dto.getOperation()==1){
            //删除redis数据
            redisTemplate.opsForSet().remove(comment_likes_key, dto.getCommentId());
            //删除mongodb中的数据
            Query query = Query.query(Criteria.where("userId").is(apUser.getId()).and("targetId").is(dto.getCommentId()));
            mongoTemplate.remove(query, ApCommentLike.class);
            //修改mongodb中的数据
            Query query1=Query.query(Criteria.where("id").is(apComment.getId()).and("likes").gt(0));
            UpdateDefinition update=new Update().inc("likes",-1);
            mongoTemplate.remove(query1, ApComment.class);
        }


        //6 如果没有点赞过，并且正在执行的是点赞操作，新增redis,新增mongo中的点赞集合，修改mongo中的评论集合，点赞数+1
        if(!memberFlag && dto.getOperation()==0){
            //新增redis
            redisTemplate.opsForSet().add(comment_likes_key,dto.getCommentId());
            //新增mongo中的点赞集合
            ApCommentLike apCommentLike=new ApCommentLike();
            apCommentLike.setId(ObjectId.get().toHexString());
            apCommentLike.setTargetId(dto.getCommentId());
            apCommentLike.setCreatedTime(new Date());
            apCommentLike.setUserId(apUser.getId());
            mongoTemplate.insert(apCommentLike);
            //修改mongo中的评论集合，点赞数+1
            Query query=Query.query(Criteria.where("id").is(apComment.getId()));
            UpdateDefinition update=new Update().inc("likes",1);
            mongoTemplate.updateFirst(query,update,ApComment.class);
        }
        //4.返回数据
        apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);

        Map map=new HashMap();
        map.put("likes",apComment.getLikes());

        return ResponseResult.okResult(map);
    }
}
